package com.songlanyun.modules.collect.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.modules.collect.model.dto.UserCollectGoodsDTO;
import com.songlanyun.modules.exception.CollectException;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.modules.goods.model.vo.GoodsSlimVo;
import com.songlanyun.modules.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.modules.collect.dao.UserCollectGoodsDao;
import com.songlanyun.modules.collect.entity.UserCollectGoods;
import com.songlanyun.modules.collect.service.UserCollectGoodsService;


@Service("userCollectGoodsService")
public class UserCollectGoodsServiceImpl extends ServiceImpl<UserCollectGoodsDao, UserCollectGoods> implements UserCollectGoodsService {


    private GoodsService goodsService;

    @Autowired
    public void setGoodsService(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    @Override
    public UserCollectGoods create(UserCollectGoods entity) {
        this.baseMapper.insert(entity);
        return entity;
    }

    @Override
    public UserCollectGoods modify(UserCollectGoods entity) {
        this.baseMapper.updateById(entity);
        return entity;
    }

    @Override
    public void remove(Long id) {
        this.baseMapper.deleteById(id);
    }

    @Override
    public UserCollectGoods addEntity(Long userId, UserCollectGoodsDTO dto) {
        UserCollectGoods collectGoods = this.getOne(new LambdaQueryWrapper<UserCollectGoods>()
                .eq(UserCollectGoods::getUserId, userId)
                .eq(UserCollectGoods::getGoodsId, dto.getGoodsId())
                .last("limit 1"));
        if (null != collectGoods) {
            throw new RRException(CollectException.COLLECT_EXITS);
        }
        Goods goods = goodsService.getById(dto.getGoodsId(), true);
        if (null == goods)
            throw new RRException(CollectException.COLLECT_SHOP_NOT_EXITS);
        collectGoods = new UserCollectGoods();
        BeanUtil.copyPropertiesIgnoreNull(dto, collectGoods);//克隆一份
        collectGoods.setUserId(userId);
        collectGoods.setShopId(goods.getShopId());
        this.create(collectGoods);
        return collectGoods;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsSlimVo> page = this.baseMapper.loadCollectList(
                new Query<UserCollectGoods>().getPage(params), MapUtil.getLong(params, "user_id")
        );
        if(page != null && page.getRecords() != null){
            // 过滤掉售价为零和库存为零的商品
            List<GoodsSlimVo> goodsSlimVoIPage = page.getRecords();
            goodsSlimVoIPage = goodsSlimVoIPage.stream().filter(g -> {
                g.loadResidualInventory();
                return (g.getMinSalePrice().compareTo(BigDecimal.ZERO) > 0 && g.getResidualInventory() > 0);
            }).collect(Collectors.toList());
            page.setRecords(goodsSlimVoIPage);
        }

        //统计商品点赞总数
        page.getRecords().forEach(g -> {
            Integer collectSum = this.baseMapper.selectCount(
                    new LambdaQueryWrapper<UserCollectGoods>()
                            .eq(UserCollectGoods::getGoodsId, g.getId())
            );
            g.setCollectSum(collectSum);
        });
        return new PageUtils(page);
    }

    @Override
    public Boolean isCollect(Long userId, Long goodsId) {
        Integer count = this.baseMapper.selectCount(
                new LambdaQueryWrapper<UserCollectGoods>()
                        .eq(UserCollectGoods::getUserId, userId)
                        .eq(UserCollectGoods::getGoodsId, goodsId)
        );

        return count > 0;
    }

    @Override
    public Integer collectSum(Long userId) {
        return this.baseMapper.selectCount(
                new LambdaQueryWrapper<UserCollectGoods>()
                        .eq(UserCollectGoods::getUserId, userId)
        );
    }

    @Override
    public void delCollect(Long userId, Long goodsId) {
        this.baseMapper.delete(
                new LambdaQueryWrapper<UserCollectGoods>()
                        .eq(UserCollectGoods::getUserId, userId)
                        .eq(UserCollectGoods::getGoodsId, goodsId)
        );
    }

}